extends Node2D

var camera_zoom := Vector2.ZERO
var shake_strength: float = 0.0
@export var camera_covery_speed: float = 16.0
@export var camera_offset := 1.0
const CAMERA_SHAKE_LIMIT = 10

@export var enemy_scene: PackedScene
@export var background_scene: PackedScene

@onready var player_init_pos: Marker2D = $PlayerInitPos
@onready var player: Player = $Player
@onready var camera_2d: Camera2D = $Camera2D
@onready var enemy_path: Path2D = $EnemyPath
@onready var enemy_spawn_location: PathFollow2D = $EnemyPath/EnemySpawnLocation
@onready var enemy_spawn_timer: Timer = $EnemySpawnTimer


func _ready() -> void:
	$Player.position = $PlayerInitPos.position
	enemy_spawn_timer.start()
	add_child(background_scene.instantiate())
	
	camera_2d.position.x = (player.position.x + player_init_pos.position.x) / 2 * camera_offset
	camera_2d.position.y = player.position.y - 200
	camera_2d.reset_smoothing()
	
	Game.reset_game_data()


func _process(delta: float) -> void:
	# Shake Camera
	var shake_offset := Vector2(
		randf_range(-shake_strength, shake_strength),
		randf_range(-shake_strength, shake_strength)
	)
	camera_2d.offset = shake_offset
	shake_strength = move_toward(shake_strength, 0, camera_covery_speed * delta)
	
	camera_2d.position.x = (player.position.x + player_init_pos.position.x) / 2 * camera_offset
	camera_2d.position.y = player.position.y - 200
	
	if enemy_spawn_timer.is_stopped():
		# 生成一拍敌人
		var row_length = 6.0
		var spawn_list = range(0, row_length + 1)
		
		# 掐头去尾
		spawn_list.pop_back()
		spawn_list.pop_front()
		for n in range(2):   # 再随机挑两个去掉
			spawn_list.pop_at(randi_range(0, spawn_list.size() - 1))
		for n in spawn_list:
			create_enemy(n / row_length)
		enemy_spawn_timer.wait_time = randf_range(0.9, 1.2)
		enemy_spawn_timer.start()


func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("attack") and player.has_attack():
		player.attack()
		var bullet := player.bullet_scene.instantiate()
		bullet.position = player.position
		add_child(bullet)
	
	if event.is_action_pressed("reload"):
		get_tree().reload_current_scene()


func shake_camera(strength: float) -> void:
	shake_strength += strength
	if shake_strength > CAMERA_SHAKE_LIMIT:
		shake_strength = CAMERA_SHAKE_LIMIT


func create_enemy(ratio=randf()) -> void:
	var enemy = enemy_scene.instantiate()
	enemy_spawn_location.progress_ratio = ratio
	enemy.position = enemy_spawn_location.position
	
	#var direction = enemy_spawn_location.rotation + PI / 2
	#enemy.rotation = direction + randf_range(-PI / 4, PI / 4)
	
	enemy.move_speed = 120 + sqrt(Game.distance + 100) * 3
	
	enemy.hit_player.connect(func ():
		shake_camera(8)
	)
	
	add_child(enemy)


func clear_enemy(area: Area2D) -> void:
	area.queue_free()
